<template>
    <div>
      <!-- 查询表单 -->
      <el-form :inline="true" :model="searchForm" class="demo-form-inline">
        <el-form-item label="">
          <el-input v-model="searchForm.storeName" placeholder="仓库名称" clearable />
        </el-form-item>
  
        <el-form-item label="">
          <el-input v-model="searchForm.outNumber" placeholder="出库单据号" clearable />
        </el-form-item>
        <el-form-item label="">
            <el-date-picker
                v-model="searchForm.outPlanTime"
                type="date"
                placeholder="选择日期"
                value-format="YYYY-MM-DD"
            />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" round @click="search">查询</el-button>
        </el-form-item>
      </el-form>
  
      <!-- 新增 -->
      <div style="display: inline;">
        <el-button type="primary" round @click="handleAdd">手工录入</el-button>
        <el-dialog v-model="addDialogVisible" title="新增出库单信息" width="500">
          <el-form :model="newPosition">
            <el-form-item label="出库单号" :label-width="formLabelWidth">
              <el-input v-model="newPosition.outNumber" autocomplete="off" />
            </el-form-item>
            <el-form-item label="计划出库时间" :label-width="formLabelWidth">
              <el-date-picker
                v-model="newPosition.outPlanTime"
                type="datetime"
                placeholder="选择日期时间"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item disabled label="业务单据号" :label-width="formLabelWidth">
              <el-input v-model="newPosition.bizNo" autocomplete="off" />
            </el-form-item>
            <el-form-item label="货物去向" :label-width="formLabelWidth">
              <el-input v-model="newPosition.goodsDestination" autocomplete="off" />
            </el-form-item>
            <el-form-item label="仓库名称" :label-width="formLabelWidth">
              <el-select v-model="newPosition.storeName" placeholder="请选择仓库">
                <el-option
                  v-for="name in warehouseList"
                  :key="name"
                  :label="name"
                  :value="name"
                />
              </el-select>
            </el-form-item>
            
            <!-- 商品列表 -->
            <el-form-item label="商品信息" :label-width="formLabelWidth">
              <div v-for="(item, index) in newPosition.goodsList" :key="index">
                <el-row :gutter="10" style="margin-bottom: 10px;">
                  <el-col :span="10">
                    <el-input v-model="item.goodsName" placeholder="商品名称" />
                  </el-col>
                  <el-col :span="10">
                    <el-input v-model="item.goodsCount" placeholder="数量" type="number" />
                  </el-col>
                  <el-col :span="4">
                    <el-button type="danger" @click="removeGoodsItem(index)" v-if="newPosition.goodsList.length > 1">删除</el-button>
                  </el-col>
                </el-row>
              </div>
              <el-button type="primary" @click="addGoodsItem">添加商品</el-button>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="addDialogVisible = false">取消</el-button>
              <el-button type="primary" @click="handleAddConfirm">确认</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
      <!-- 导出按钮 -->
        <download-excel download-excel
            class = "export-excel-wrapper"
            :data = "tableData.resultList"
            name = "download.xls">
            <el-button type="warning" round @click="handleExport">导出数据</el-button>
        </download-excel>
      <div style="height: 20px;"></div>
  
      <!-- 数据展示区域 -->
      <el-table :data="tableData.resultList" border style="width: 100%" max-height="500">
        <el-table-column prop="id" sortable label="序号">
          <template #default="scope">
            {{ parseInt(scope.row.id) }}
          </template>
        </el-table-column>
        <el-table-column prop="outNumber" sortable label="出库单据号"  />
        <el-table-column prop="storeName" sortable label="仓库名称" />
        <el-table-column prop="goodsDestination" sortable label="商品去向" />
        <el-table-column prop="outPlanTime" sortable label="计划出库时间" />
        <el-table-column prop="outStatus" sortable label="出库状态">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.outStatus)">
              {{ getStatusText(scope.row.outStatus) }}
            </el-tag>
          </template>
        </el-table-column>
  
        <el-table-column prop="createTime" sortable label="创建时间" />
        <el-table-column prop="createName" sortable label="创建人" />
        <el-table-column prop="updateTime" sortable label="修改时间" />
        <el-table-column prop="updateName" sortable label="修改人" />
        
        <!-- 修改操作列按钮绑定 -->
        <el-table-column fixed="right" label="操作" width="200">
          <template #default="scope">
            <template v-if="scope.row.outStatus !== '1' && scope.row.outStatus !== '2'">
              <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
              <!-- <el-button type="success" size="small" @click="handleConfirm(scope.row)">确认</el-button> -->
              <el-button type="warning" size="small" @click="handlePostpone(scope.row)">推迟</el-button>
              <el-button type="danger" size="small" @click="handleCancel(scope.row)">取消</el-button>
            </template>
            <el-button type="info" size="small" @click="handleDetail(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <!-- 信息修改 -->
      <el-dialog v-model="editDialogVisible" title="编辑出库单信息" width="500">
        <el-form :model="editForm">
          <el-form-item label="出库单号" :label-width="formLabelWidth">
            <el-input v-model="editForm.outNumber" autocomplete="off" />
          </el-form-item>
          <el-form-item label="计划出库时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="editForm.outPlanTime"
              type="datetime"
              placeholder="选择日期时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item disabled label="业务单据号" :label-width="formLabelWidth">
            <el-input v-model="editForm.bizNo" autocomplete="off" />
          </el-form-item>
          <el-form-item label="货物去向" :label-width="formLabelWidth">
            <el-input v-model="editForm.goodsDestination" autocomplete="off" />
          </el-form-item>
          <el-form-item label="仓库名称" :label-width="formLabelWidth">
            <el-select v-model="editForm.storeName" placeholder="请选择仓库">
              <el-option
                v-for="name in warehouseList"
                :key="name"
                :label="name"
                :value="name"
              />
            </el-select>
          </el-form-item>
          
          <!-- 商品列表 -->
          <el-form-item label="商品信息" :label-width="formLabelWidth">
            <div v-for="(item, index) in editForm.goodsList" :key="index">
              <el-row :gutter="10" style="margin-bottom: 10px;">
                <el-col :span="10">
                  <el-input v-model="item.goodsName" placeholder="商品名称" />
                </el-col>
                <el-col :span="10">
                  <el-input v-model="item.goodsCount" placeholder="数量" type="number" />
                </el-col>
                <el-col :span="4">
                  <el-button type="danger" @click="removeGoodsItem(index)" v-if="editForm.goodsList.length > 1">删除</el-button>
                </el-col>
              </el-row>
            </div>
            <el-button type="primary" @click="addGoodsItem">添加商品</el-button>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handleEditConfirm">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 详情对话框 -->
      <el-dialog v-model="detailDialogVisible" title="出库单详情" width="800">
        <!-- 基本信息 -->
        <div class="detail-section">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="出库单据号">{{ detailData.outNumber }}</el-descriptions-item>
            <el-descriptions-item label="仓库名称">{{ detailData.storeName }}</el-descriptions-item>
            <el-descriptions-item label="货物去向">{{ detailData.goodsDestination }}</el-descriptions-item>
            <el-descriptions-item label="计划出库时间">{{ detailData.outPlanTime }}</el-descriptions-item>
            <el-descriptions-item label="出库状态">{{ detailData.outStatus === '1' ? '启用' : '未出库' }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ detailData.createTime }}</el-descriptions-item>
            <el-descriptions-item label="创建人">{{ detailData.createName }}</el-descriptions-item>
            <el-descriptions-item label="修改时间">{{ detailData.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="修改人">{{ detailData.updateName }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <!-- 商品列表 -->
        <div class="detail-section">
          <h3>商品信息</h3>
          <el-table :data="goodsList" border style="width: 100%">
            <el-table-column prop="goodsName" label="商品名称" />
            <el-table-column prop="goodsCount" label="数量" />
          </el-table>
        </div>

        <template #footer>
          <div class="dialog-footer">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </div>
        </template>
      </el-dialog>
  
      <!-- 添加推迟对话框 -->
      <el-dialog v-model="postponeDialogVisible" title="推迟出库时间" width="400">
        <el-form :model="postponeForm">
          <el-form-item label="新计划时间" :label-width="formLabelWidth">
            <el-date-picker
              v-model="postponeForm.outPlanTime"
              type="datetime"
              placeholder="选择新的计划时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="postponeDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="handlePostponeConfirm">确认</el-button>
          </div>
        </template>
      </el-dialog>

      <!-- 分页区域 -->
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="searchCondition.pageNum"
          v-model:page-size="searchCondition.pageSize"
          :page-sizes="[5, 10, 15, 20]"
          :size="size"
          :disabled="disabled"
          :background="background"
          layout="total, sizes, prev, pager, next, jumper"
          :total="tableData.totalNum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </template>
  
  
<script setup>
import { ref, reactive, onMounted } from 'vue'  
import { ElMessage } from 'element-plus'
import {searchWareHouseName, searchOutStore,searchOutStoreGoods,addOutStore,updateOutStore,updateOutStatus } from '../api/api.js'

// 表格数据对象
const tableData = ref([])
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const formLabelWidth = '120px'

// 搜索表单数据
const searchForm = reactive({
  storeName: '',
  outNumber: '',   
  outPlanTime: ''
})

// 搜索条件
const searchCondition = reactive({
  storeName: '',   
  outNumber: '',
  outPlanTime: '',   
  pageNum: 1,      
  pageSize: 10     
})

// 新增表单数据
const newPosition = reactive({
  bizNo: '',         // 业务单号
  goodsDestination: '', // 货物去向
  outNumber: '',     // 出库单号
  outPlanTime: '',   // 计划出库时间
  storeName: '',     // 仓库名称
  goodsList: [{      // 商品列表
    goodsCount: 1,
    goodsName: ''
  }]
})

// 修改编辑表单数据结构，与新增保持一致
const editForm = reactive({
  bizNo: '',         // 业务单号
  goodsDestination: '', // 货物去向
  outNumber: '',     // 出库单号
  outPlanTime: '',   // 计划出库时间
  storeName: '',     // 仓库名称
  goodsList: [{      // 商品列表
    goodsCount: 1,
    goodsName: ''
  }]
})

// 仓库列表数据
const warehouseList = ref([])

// 获取仓库列表
const getWarehouseList = async () => {
  try {
    const res = await searchWareHouseName()
    if (res.data.code === 200) {
      warehouseList.value = res.data.data
      // console.log('仓库列表:', warehouseList.value) 
    } else {
      ElMessage.warning('获取仓库列表失败')
    }
  } catch (error) {
    console.error('获取仓库列表失败:', error)
    ElMessage.error('获取仓库列表失败')
  }
}

// 详情对话框显示状态和数据
const detailDialogVisible = ref(false)
const detailData = reactive({
  outNumber: '',
  storeName: '',
  goodsDestination: '',
  outPlanTime: '',
  outStatus: '',
  createTime: '',
  createName: '',
  updateTime: '',
  updateName: ''
})
const goodsList = ref([])

// 添加推迟对话框控制
const postponeDialogVisible = ref(false)
const postponeForm = reactive({
  id: 0,
  outPlanTime: '',
  outStatus: '3'  // 推迟状态
})

// 查询列表
const search = async () => {
  try {
    searchCondition.outNumber = searchForm.outNumber
    searchCondition.storeName = searchForm.storeName
    searchCondition.outPlanTime = searchForm.outPlanTime
    const res = await searchOutStore(searchCondition)
    if (res.data.code === 200) {
      tableData.value = res.data.data
      ElMessage.success('查询成功')
    } else {
      ElMessage.warning(res.data.msg || '查询失败')
    }
  } catch (error) {
    console.error('查询失败:', error)
    ElMessage.error('查询失败: ' + (error.message || '未知错误'))
  }
}

// 页面方法
const handleAdd = async () => {
  Object.keys(newPosition).forEach(key => {
    if (key === 'goodsList') {
      newPosition.goodsList = [{
        goodsId: 0,
        goodsName: '',
        goodsCount: 1
      }]
    } else {
      newPosition[key] = ''
    }
  })
  newPosition.outStatus = '0'
  await getWarehouseList() // 获取仓库列表
  addDialogVisible.value = true
}

const handleAddConfirm = async () => {
  try {
    // 检查必填字段
    if (!newPosition.outNumber || !newPosition.storeName || !newPosition.outPlanTime) {
      return ElMessage.warning('请填写完整信息')
    }

    // 检查商品列表
    if (!newPosition.goodsList.every(item => item.goodsName && item.goodsCount > 0)) {
      return ElMessage.warning('请完善商品信息')
    }

    // 提交数据
    const submitData = {
      ...newPosition,
      goodsList: newPosition.goodsList.map(item => ({
        goodsName: item.goodsName,
        goodsCount: parseInt(item.goodsCount)
      }))
    }
    
    await addOutStore(submitData)
    ElMessage.success('新增成功')
    addDialogVisible.value = false
    search() // 刷新列表
  } catch (error) {
    console.error('新增失败:', error)
    ElMessage.error('新增失败: ' + (error.message || '未知错误'))
  }
}

/**
 * 编辑对话框
 */
const handleEdit = async (row) => {
  // 先复制基本信息
  Object.assign(editForm, row)
  await getWarehouseList() // 获取仓库列表
  editDialogVisible.value = true
  
  try {
    // 获取商品列表
    const res = await searchOutStoreGoods(parseInt(row.id))
    if (res.data && res.data.data) {
      // 转换数据结构以适应表单
      editForm.goodsList = res.data.data.map(item => ({
        goodsId: item.goodsId,
        goodsName: item.goodsName || '',
        goodsCount: item.goodsCount
      }))
    } else {
      // 如果没有数据则显示空商品项
      editForm.goodsList = [{
        goodsId: 0,
        goodsName: '',
        goodsCount: 1
      }]
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    ElMessage.warning('获取商品列表失败')
    // 显示空商品项
    editForm.goodsList = [{
      goodsId: 0,
      goodsName: '',
      goodsCount: 1
    }]
  }
}

/**
 * 编辑确认提交
 */
const handleEditConfirm = async () => {
  try {
    const updateData = {
      ...editForm,
      id: parseInt(editForm.id), // 确保id为数值类型
      goodsList: editForm.goodsList.map(item => ({
        goodsId: parseInt(item.goodsId),
        goodsName: item.goodsName,
        goodsCount: parseInt(item.goodsCount)
      }))
    }
    
    await updateOutStore(updateData)
    ElMessage.success('修改成功')
    search()
    editDialogVisible.value = false
  } catch (error) {
    console.error('修改失败:', error)
    ElMessage.error('修改失败: ' + (error.message || '未知错误'))
  }
}

// 详情按钮点击事件
const handleDetail = async (row) => {
  // 先显示基本信息
  Object.assign(detailData, row)
  detailDialogVisible.value = true
  
  try {
    // 尝试获取商品列表
    const res = await searchOutStoreGoods(parseInt(row.id))
    if (res.data && res.data.data) {
      goodsList.value = res.data.data
    } else {
      goodsList.value = [] // 如果没有数据则显示空列表
    }
  } catch (error) {
    console.error('获取商品列表失败:', error)
    goodsList.value = [] // 发生错误时显示空列表
    ElMessage.warning('获取商品列表失败')
  }
}

// 分页方法
const handleSizeChange = (val) => {
  searchCondition.pageSize = val
  search()
}

const handleCurrentChange = (val) => {
  searchCondition.pageNum = val
  search()
}

// 商品列表方法
const addGoodsItem = () => {
  const target = editDialogVisible.value ? editForm : newPosition
  target.goodsList.push({
    goodsId: 0,
    goodsName: '',
    goodsCount: 1
  })
}

const removeGoodsItem = (index) => {
  const target = editDialogVisible.value ? editForm : newPosition
  target.goodsList.splice(index, 1)
}

/**
 * 确认按钮点击事件
 */
const handleConfirm = async (row) => {
  try {
    await updateOutStatus({
      id: parseInt(row.id),
      outStatus: '1'  // 修改为确认状态
    })
    ElMessage.success('确认成功')
    search()  // 刷新列表
  } catch (error) {
    ElMessage.error('确认失败')
  }
}

/**
 * 取消按钮点击事件
 */
const handleCancel = async (row) => {
  try {
    await updateOutStatus({
      id: parseInt(row.id),
      outStatus: '2'  // 修改为取消状态
    })
    ElMessage.success('取消成功')
    search()  // 刷新列表
  } catch (error) {
    ElMessage.error('取消失败')
  }
}

/**
 * 显示推迟对话框
 */
const handlePostpone = (row) => {
  postponeForm.id = parseInt(row.id)
  postponeForm.outPlanTime = ''
  postponeDialogVisible.value = true
}

/**
 * 确认推迟
 */
const handlePostponeConfirm = async () => {
  try {
    if (!postponeForm.outPlanTime) {
      return ElMessage.warning('请选择新的计划时间')
    }
    await updateOutStatus({
      outId: postponeForm.id,
      outPlanTime: postponeForm.outPlanTime,
      outStatus: '3'  // 修改为推迟状态
    })
    ElMessage.success('推迟成功')
    postponeDialogVisible.value = false
    search()  // 刷新列表
  } catch (error) {
    ElMessage.error('推迟失败')
  }
}

/**
 * 获取状态文本
 */
const getStatusText = (status) => {
  switch (status) {
    case '0':
      return '未出库'
    case '1':
      return '已出库'
    case '2':
      return '取消'
    case '3':
      return '推迟'
    default:
      return '未知状态'
  }
}

/**
 * 获取状态标签类型
 */
const getStatusType = (status) => {
  switch (status) {
    case '0':
      return 'default'  // 未出库 - 默认
    case '1':
      return 'success'  // 已出库 - 绿色
    case '2':
      return 'info'     // 取消 - 灰色
    case '3':
      return 'danger'   // 推迟 - 红色
    default:
      return ''
  }
}

onMounted(() => {
  search()
})
</script>

<style scoped>
 .demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.operation-area {
  margin: 15px 0;
}

.pagination-area {
  margin-top: 20px;
  text-align: right;
}

.detail-section {
  margin-bottom: 20px;
}

.detail-section h3 {
  margin-bottom: 15px;
  font-weight: bold;
}
</style>